package com.android.meige.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.meige.R;
import com.android.meige.activity.mine.TransparentActivity;
import com.android.meige.adapt.MainlistAdapt;
import com.android.meige.app.BaseActivity;
import com.android.meige.enums.EJumpStatus;
import com.android.meige.model.group.AdPictureData;
import com.android.meige.model.group.AdPictureDataCallback;
import com.android.meige.model.group.MainList;
import com.android.meige.model.group.MainListCallback;
import com.android.meige.pojo.BannerUintPojo;
import com.android.meige.utils.ConstantsUrl;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.JumpUtils;
import com.android.meige.utils.MyLog;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.utils.ReleaseManager;
import com.android.meige.view.group.VRefreshLayout;
import com.android.meige.view.recycleview.CustomLoadMoreView;
import com.android.meige.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class MainRecommendType extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener, View.OnClickListener {

    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.click_resetnetwork_msg)
    TextView clickResetnetworkMsg;
    @BindView(R.id.click_resetnetwork_refresh)
    TextView clickResetnetworkRefresh;
    @BindView(R.id.main_top_share)
    ImageView main_top_share;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    private boolean networkConnected;
    private MainlistAdapt adapter;
    private int page = 1;
    private MainRecommendType mcontext;
    private String type;
    private String sorttitle;
    private LinearLayoutManager mLayoutManager;
    private View head;
    private String shareurl;
    private String sharethumb;
    private String sharecontent = "";
    private String return_type;
    private LinearLayout llthematic1;
    private ImageView thematic1;
    private ImageView thematic2;
    private List<AdPictureData.DataBean.AdBean> adList;
    private ImageView bannerView;
    private List<AdPictureData.DataBean.AdBean> bannerList;
    private GridLayoutManager mGridLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_recycle_refresh);
        ButterKnife.bind(this);
        mcontext = MainRecommendType.this;
        sorttitle = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_TITLE);
        type = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_LINK);
        return_type = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.RETURN_TYPE);
        switch (sorttitle) {
            case "免费试用":
            case "试用团":
                type = "2";
                break;
            case "每日抽奖":
            case "抽奖团":
                type = "5";
                break;
            case "邻居团":
            case "AA团":
                type = "6";
                break;
            default:
                type = "1";
                break;
        }
//        main_top_share.setVisibility(View.VISIBLE);
        initTitle(0, sorttitle);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initUI();
        if (networkConnected) {
            GetTypeData(true);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    private void initRecycle() {

        adapter = new MainlistAdapt(mcontext, null, type);
        //  adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
//                mRecyclerView.setLayoutManager(mLayoutManager);
//                mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) findViewById(R.id.top), 0);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {

                if (return_type != null) {
                    if (JumpUtils.IsRegmatch(return_type, EJumpStatus.ELottery.getRegmatch())) {
                        int showId = getShowId(position);
                        ObjectUtils.ToDetailActivity(mcontext, showId, adapter.getItem(position).getId(), "");
                        return;
                    } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumFreeTest.getRegmatch())) {
                        int showId = getShowId(position);
                        ObjectUtils.ToDetailActivity(mcontext, showId, adapter.getItem(position).getId(), "");
                        return;
                    } else {
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        return;
                    }
                }

                switch (sorttitle) {
                    case "每日抽奖":
                    case "抽奖团":
                    case "免费试用":
                    case "试用团":
                        int showId = getShowId(position);
                        ObjectUtils.ToDetailActivity(mcontext, showId, adapter.getItem(position).getId(), "");
                        break;
                    default:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                }

            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.main_list_item_go_kai:
                    case R.id.ll_free:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                    case R.id.ll_start_soon:
                        ObjectUtils.ToDetailActivity(mcontext, 3, adapter.getItem(position).getId(), "");
                        break;
                    case R.id.ll_result:
                        Intent intent = new Intent(mcontext, BaseObject.class);
                        if(type.equals("2")){
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "试用结果");
                        }else if(type.equals("5")){
                            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "中奖名单");
                        }
                        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, adapter.getItem(position).getId());
                        startActivity(intent);
                        break;

                }
                return false;
            }
        });
    }

    private int getShowId(int position) {
        int end = Integer.parseInt(adapter.getItem(position).getEnd_time());
        int start = Integer.parseInt(adapter.getItem(position).getStart_time());
        int run = adapter.getItem(position).getRun_time();
        if (run > end && run > start) {
            return 5;
        } else if (run > start && run < end) {
            return 1;
        } else if (run < start) {
            return 3;
        }else {
            return 1;
        }
    }

    private void initUI() {
        head = getLayoutInflater().inflate(R.layout.item_list_sort_dapai, null, false);
        head.findViewById(R.id.ll_msg).setVisibility(View.GONE);
        bannerView = (ImageView) head.findViewById(R.id.item_list_sort_dapai_img);
        bannerView.setOnClickListener(this);
        initRecycle();

        if (return_type != null) {
            if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumFreeTest.getRegmatch())) {
                adapter.addHeaderView(head);
                Refresh();
                return;
            } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.ELottery.getRegmatch())) {
                adapter.addHeaderView(head);
                Refresh();
                return;
            } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumNew.getRegmatch())) {
                adapter.addHeaderView(head);
                findTicView();
                Refresh();
                return;
            }
        }

        switch (sorttitle) {
            case "品牌折扣":
                break;
            case "免费试用":
            case "试用团":
                adapter.addHeaderView(head);
                break;
            case "每日抽奖":
            case "抽奖团":
                adapter.addHeaderView(head);
                break;
            case "新人专享":
            case "新专团":
                adapter.addHeaderView(head);
                findTicView();
                break;
            default:
                break;
        }
        Refresh();
    }

    private void findTicView() {
        llthematic1 = (LinearLayout) head.findViewById(R.id.ll_thematic1);
        thematic1 = (ImageView) head.findViewById(R.id.thematic1);
        thematic2 = (ImageView) head.findViewById(R.id.thematic2);
        thematic1.setOnClickListener(this);
        thematic2.setOnClickListener(this);
    }

    private void Refresh() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                page = 1;
                                GetTypeData(true);
                                mRefreshLayout.refreshComplete();
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    @OnClick({R.id.click_resetnetwork_refresh, R.id.main_top_share})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetTypeData(true);
                break;
            case R.id.main_top_share:
                Intent share = new Intent(mcontext, TransparentActivity.class);
                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TYPE, 1);
                share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_CONTENT, "这么划算真的不来抢吗");
                if (return_type != null) {
                    if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumPromote.getRegmatch())) {
                        promoteToShare(share);
                    }
                    return;
                }

                switch (sorttitle) {
                    case "推广团":
                        promoteToShare(share);
                        break;
                }
                break;
            case R.id.thematic1:
                jumpFromAD(adList, 0);
                break;
            case R.id.thematic2:
                jumpFromAD(adList, 1);
                break;
            case R.id.item_list_sort_dapai_img:
                jumpFromAD(bannerList, 0);
                break;
        }
    }

    private void promoteToShare(Intent share) {
        shareurl = ConstantsUrl.baseDomain + "goods/index/?typeid=8";
        String appName = getResources().getString(R.string.app_name);
        share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_TITLE, appName + "~" + sharecontent);
        share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_IMAGEURL, sharethumb);
        share.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_TRANS_SHOW_LINK, shareurl);
        mcontext.startActivity(share);
    }

    private void jumpFromAD(List<AdPictureData.DataBean.AdBean> list, int position) {
        if (list != null && list.size() > position) {
            BannerUintPojo Apojo = new BannerUintPojo();
            AdPictureData.DataBean.AdBean adBean = list.get(position);
            Apojo.return_type = adBean.getAnurl();
            Apojo.title = "";
            if (JumpUtils.jumpToEveryWhere(mcontext, Apojo, null))
                return;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetTypeData(false);
    }

    private void GetTypeData(boolean isloadhead) {

        if (return_type != null) {
            if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumPromote.getRegmatch())) {
                main_top_share.setVisibility(View.VISIBLE);
                GetListData(page, "&typeid=8");
                return;
            } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.ELottery.getRegmatch())) {
                if (isloadhead) {
                    GetDataBanner("6");
                }
                GetListData(page, "&typeid=6&order=lottery");
                return;
            } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumFreeTest.getRegmatch())) {
                if (isloadhead) {
                    GetDataBanner("5");
                }
                GetListData(page, "&typeid=5&order=lottery");
                return;
            } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumNew.getRegmatch())) {
                ReleaseManager.printLog("GetListData", return_type);
                if (isloadhead) {
                    GetDataBanner("7");
                    getADData("8");
                }
                GetListData(page, "&typeid=2");
                return;
            } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumNeighbor.getRegmatch())) {
                GetListData(page, "&typeid=7");
                return;
            } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumLadder.getRegmatch())) {
                GetListData(page, "&typeid=10");
                return;
            } else if (JumpUtils.IsRegmatch(return_type, EJumpStatus.EnumSelf.getRegmatch())) {
                GetListData(page, "&typeid=9");
                return;
            }
        }

        switch (sorttitle) {
            case "推广团":
                main_top_share.setVisibility(View.VISIBLE);
                GetListData(page, "&typeid=8");
                break;
            case "每日抽奖":
            case "抽奖团":
                if (isloadhead) {
                    GetDataBanner("6");
                }
                GetListData(page, "&typeid=6&order=lottery");
                break;
            case "新人专享":
            case "新专团":
                if (isloadhead) {
                    GetDataBanner("7");
                    getADData("8");
                }
                GetListData(page, "&typeid=2");
                break;
            case "免费试用":
            case "试用团":
            case "助享免单":
                if (isloadhead) {
                    GetDataBanner("5");
                }
                GetListData(page, "&typeid=5&order=lottery");
                break;
            case "邻居团":
            case "AA团":
                GetListData(page, "&typeid=7");
                break;
            case "9":
            case "自选团":
                //自选
                GetListData(page, "&typeid=9");
                break;
            case "10":
            case "阶梯团":
                //阶梯
                GetListData(page, "&typeid=10");
                break;
        }
    }

    /**
     * 轮播图
     */
    private void GetDataBanner(String typeid) {
        String address = ConstantsUrl.domain + ConstantsUrl.ADVERTISEPICTURE;
        MyLog.e("地址", address);
        HashMap<String, String> map = new HashMap<>();
        map.put("typeid", typeid);
        HttpUtils.get(address, map, new AdPictureDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                adapter.removeHeaderView(head);
            }

            @Override
            public void onResponse(AdPictureData response, int id) {
                if (response == null) {
                    adapter.removeHeaderView(head);
                    return;
                }
                AdPictureData.DataBean data = response.getData();
                if (data != null && ObjectUtils.listHasData(data.getAd())) {
                    bannerList = data.getAd();
                    ObjectUtils.photo2(mcontext, bannerList.get(0).getPath(), bannerView);
                    sharethumb = data.getAd().get(0).getPath();
                } else {
                    adapter.removeHeaderView(head);
                }
            }
        });
    }

    private void getADData(String typeid) {
        String address = ConstantsUrl.domain + ConstantsUrl.ADVERTISEPICTURE;
        HashMap<String, String> map = new HashMap<>();
        map.put("typeid", typeid);
        HttpUtils.get(address, map, new AdPictureDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                adapter.removeHeaderView(head);
            }

            @Override
            public void onResponse(AdPictureData response, int id) {
                if (response == null) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                    return;
                }
                AdPictureData.DataBean data = response.getData();
                if (data != null && ObjectUtils.listHasData(data.getAd())) {
                    adList = data.getAd();
                    if (ObjectUtils.listHasData(adList)) {
                        llthematic1.setVisibility(View.VISIBLE);
                        ObjectUtils.photo2(mcontext, adList.get(0).getPath(), thematic1);
                        if (adList.size() > 1) {
                            ObjectUtils.photo2(mcontext, adList.get(1).getPath(), thematic2);
                        }
                    }
                } else {
                    llthematic1.setVisibility(View.GONE);
                }
            }
        });
    }

    //获取主页列表数据
    private void GetListData(final int page, String linktype) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA + "?page=" + page + linktype;
            MyLog.e("地址", address);
            HttpUtils.get(address, null, new MainListCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MainList response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        MainList.MainListdata data = response.getData();
                        if (data == null || !ObjectUtils.listHasData(data.getList())) {
                            if (page == 1) {
                                noData.setVisibility(View.VISIBLE);
                            } else {
                                adapter.loadMoreEnd();
                            }
                            return;
                        }
                        List<MainList.MainListdata.Mainlistdata> list = data.getList();
                        ArrayList<MainList.MainListdata.Mainlistdata> listdata = new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            MainList.MainListdata.Mainlistdata mainlistdata = list.get(i);
                            mainlistdata.setItemType(data.getList_type());
                            listdata.add(mainlistdata);
                        }
                        if (page == 1) {
                            if (data.getList_type() == 0) {
                                mRecyclerView.setLayoutManager(mLayoutManager);
                                mRecyclerView.setAdapter(adapter);
                            } else {
                                mRecyclerView.setLayoutManager(mGridLayoutManager);
                                mRecyclerView.setAdapter(adapter);
                            }
                            adapter.setNewData(listdata);
                        } else {
                            adapter.addData(listdata);
                            adapter.loadMoreComplete();
                        }
                        sharethumb = list.get(0).getThumb();
                    } else {
                        if (page == 1) {
                            noData.setVisibility(View.VISIBLE);
                        } else {
                            adapter.loadMoreFail();
                            ObjectUtils.toast(mcontext, response.getMsg());
                        }
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }
}
